package com.cqjtu.store.product.service.impl;

import com.cqjtu.store.common.PageDTO;
import com.cqjtu.store.common.PageVO;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.favorite.mapper.FavoriteMapper;
import com.cqjtu.store.favorite.pojo.entity.Favorite;
import com.cqjtu.store.product.mapper.ProductCategoryMapper;
import com.cqjtu.store.product.mapper.ProductMapper;
import com.cqjtu.store.product.pojo.dto.ProductCategoryPageDTO;
import com.cqjtu.store.product.pojo.dto.ProductSettlementDTO;
import com.cqjtu.store.product.pojo.entity.Product;
import com.cqjtu.store.product.pojo.entity.ProductCategory;
import com.cqjtu.store.cart.pojo.dto.entity.ShoppingCart;
import com.cqjtu.store.product.pojo.vo.*;
import com.cqjtu.store.product.service.ProductService;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private FavoriteMapper favoriteMapper;

    /**
     * 获取商品分类列表
     * @param parent
     * @return
     */
    @Override
    public List<ProductCategoryVO> getProductCategoryList(Integer parent) {
        List<ProductCategory> productCategoryList = productMapper.getProductCategoryList(parent);
        if(productCategoryList.isEmpty()){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有数据");
        }
        List<ProductCategoryVO> categoryVOList = new ArrayList<>();

        //封装
        productCategoryList.forEach(productCategory -> {
            ProductCategoryVO categoryVO = new ProductCategoryVO();
            categoryVO.setId(productCategory.getId());
            categoryVO.setName(productCategory.getName());
            categoryVO.setParentId(productCategory.getParentId());
            categoryVOList.add(categoryVO);
        });
        return categoryVOList;
    }

    /**
     * 查询购物车列表
     * @param userLoginVO
     * @return
     */
    @Override
    public List<ShoppingCartVO> getShoppingCartList(UserLoginVO userLoginVO) {
        //根据用户id获取用户的购物车信息
        List<ShoppingCart> shoppingCartList = productMapper.getShoppingCartList(userLoginVO.getId());
        if(shoppingCartList.isEmpty()){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户购物车没有数据");
        }
        List<ShoppingCartVO> shoppingCartVOList = new ArrayList<>();
        //封装
        shoppingCartList.forEach(shoppingCart -> {
            ShoppingCartVO shoppingCartVO = new ShoppingCartVO();
            shoppingCartVO.setId(shoppingCart.getId());
            shoppingCartVO.setUserId(shoppingCart.getId());
            shoppingCartVO.setProductId(shoppingCart.getProductId());
            shoppingCartVO.setPrice(shoppingCart.getPrice());
            shoppingCartVO.setNum(shoppingCart.getNum());
            shoppingCartVO.setCreatedUser(shoppingCart.getCreatedUser());
            shoppingCartVO.setCreatedTime(shoppingCart.getCreatedTime());
            shoppingCartVO.setModifiedUser(shoppingCart.getModifiedUser());
            shoppingCartVO.setModifiedTime(shoppingCart.getModifiedTime());
            //获取根据商品的id查询商品标题和图片路径
            Product product = productMapper.getProductById(shoppingCart.getProductId());
            shoppingCartVO.setTitle(product.getTitle());
            shoppingCartVO.setImage(product.getImage());
            shoppingCartVOList.add(shoppingCartVO);

        });
        return shoppingCartVOList;
    }

    @Override
    public List<ProductVO> getNewList() {
        List<Product> newList = productMapper.getNewList();
        List<ProductVO> productVOList = new ArrayList<>();
        newList.forEach(product -> {
            ProductVO productVO = new ProductVO();
            productVO.setId(product.getId());
            productVO.setTitle(product.getTitle());
            productVO.setPrice(product.getPrice());
            productVO.setImage(product.getImage());
            productVOList.add(productVO);
        });
        return productVOList;
    }

    @Override
    public List<ProductVO> getHotList() {
        List<Product> hotList = productMapper.getHotList();
        List<ProductVO> productVOList = new ArrayList<>();
        hotList.forEach(product -> {
            ProductVO productVO = new ProductVO();
            productVO.setId(product.getId());
            productVO.setTitle(product.getTitle());
            productVO.setPrice(product.getPrice());
            productVO.setImage(product.getImage());
            productVOList.add(productVO);
        });
        return productVOList;
    }

    @Override
    public PageVO<List<ProductListVO>> getListByCategoryId(ProductCategoryPageDTO categoryPageDTO,UserLoginVO userLoginVO) {
        //判断该商品分类id是否存在
        ProductCategory productCategory = productCategoryMapper.getById(categoryPageDTO.getCategoryId());
        if(productCategory == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品分类不存在");
        }
//        List<Product> productList = productMapper.getListByCategoryId(categoryPageDTO.getCategoryId());
        List<Product> productList = productMapper.getProductByPage(categoryPageDTO);
        if(productList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品分类没有商品");
        }

        //封装成VO
//        List<ProductVO> productVOList = new ArrayList<>();
//        productList.forEach(product -> {
//            ProductVO productVO = new ProductVO();
//            productVO.setId(product.getId());
//            productVO.setTitle(product.getTitle());
//            productVO.setPrice(product.getPrice());
//            productVO.setImage(product.getImage());
//            productVOList.add(productVO);
//        });
        //封装成分页当中的data
        List<ProductListVO> productVOList = new ArrayList<>();
        //判断这一系列的商品是否被收藏
        productList.forEach(product -> {
            ProductListVO productListVO =new ProductListVO();
            Favorite favorite = favoriteMapper.getFavorite(product.getId(),userLoginVO.getId());
            productListVO.setId(product.getId());
            productListVO.setTitle(product.getTitle());
            productListVO.setPrice(product.getPrice());
            productListVO.setImage(product.getImage());
            if(favorite!=null){
                //设置收藏
                productListVO.setIsFavorite(1);
            }
            productVOList.add(productListVO);
        });
        //商品数量
        int count = productMapper.count(productCategory.getId());
        PageVO<List<ProductListVO>> pageVO = new PageVO<>(categoryPageDTO.getPageIndex(), categoryPageDTO.getPageSize(), count,productVOList);
        return pageVO;
    }

    /**
     * 根据商品分类id，分页查询
     * @param categoryPageDTO
     * @return
     */
    @Override
    public PageInfo<Product> getListByCategoryId(ProductCategoryPageDTO categoryPageDTO) {
        //判断该商品分类id是否存在
        ProductCategory productCategory = productCategoryMapper.getById(categoryPageDTO.getCategoryId());
        if(productCategory == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品分类不存在");
        }
        //开启分页：设置分页参数
        PageHelper.startPage(categoryPageDTO.getPageIndex(), categoryPageDTO.getPageSize());

        List<Product> productList = productMapper.getListByCategoryId(categoryPageDTO.getCategoryId());
        if(productList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品分类没有商品");
        }
        //封装成VO
//        List<ProductVO> productVOList = new ArrayList<>();
//        productList.forEach(product -> {
//            ProductVO productVO = new ProductVO();
//            productVO.setId(product.getId());
//            productVO.setTitle(product.getTitle());
//            productVO.setPrice(product.getPrice());
//            productVO.setImage(product.getImage());
//            productVOList.add(productVO);
//        });
        //封装成页
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        return pageInfo;
    }

    @Override
    public PageVO<List<ProductVO>> getListByCategoryId3(ProductCategoryPageDTO categoryPageDTO) {
        //判断该商品分类id是否存在
        ProductCategory productCategory = productCategoryMapper.getById(categoryPageDTO.getCategoryId());
        if(productCategory == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品分类不存在");
        }
        //调用持久层方法
        List<Product> productList = productMapper.getProductByPage(categoryPageDTO);
        if(productList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品分类没有商品");
        }
        List<ProductVO> productVOList = new ArrayList<>();
        productList.forEach(product -> {
            ProductVO productVO = new ProductVO();
            productVO.setId(product.getId());
            productVO.setTitle(product.getTitle());
            productVO.setPrice(product.getPrice());
            productVO.setImage(product.getImage());
            productVOList.add(productVO);
        });
        int count = productMapper.count(categoryPageDTO.getCategoryId());
        PageVO<List<ProductVO>> pageVO = new PageVO<>(categoryPageDTO.getPageIndex(),categoryPageDTO.getPageSize(),count,productVOList);
        return pageVO;
    }

    @Override
    public ProductDetailsVO getProductDetailsById(Integer id,UserLoginVO userLoginVO) {
        //判断这个id是否合法
        Product product = productMapper.getProductDetailsById(id);
        if(product == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有此商品");
        }
        //有商品
        Favorite favorite = null;
        if(userLoginVO != null){
            //登录过，是否被当前用户收藏过了
            Integer userId = userLoginVO.getId();
            //根据商品编号以及用户编号去查询收藏表，检查该商品是否被收藏
            favorite = favoriteMapper.getFavorite(id,userId);
        }
        //封装VO
        ProductDetailsVO productDetailsVO = new ProductDetailsVO();
        productDetailsVO.setId(product.getId());
        productDetailsVO.setTitle(product.getTitle());
        productDetailsVO.setImage(product.getImage());
        productDetailsVO.setSellPoint(product.getSellPoint());
        productDetailsVO.setPrice(product.getPrice());
        if(favorite!=null){
            //被收藏了
            productDetailsVO.setIsFavority(1);
        }
        return productDetailsVO;
    }

    /**
     * 根据用户id分页查询收藏商品列表
     * @param userLoginVO
     * @return
     */
    @Override
    public PageVO<List<ProductVO>> getFavoriteListByUser(PageDTO pageDTO, UserLoginVO userLoginVO) {
        //分页查询用户收藏的商品列表
        List<Favorite> favoriteList = favoriteMapper.getFavoriteByPage(pageDTO.getOffset(),pageDTO.getPageSize(),userLoginVO.getId());
        if(favoriteList==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户没有收藏商品");
        }
        List<ProductVO> productVOList = new ArrayList<>();
        favoriteList.forEach(favorite -> {
            Product product = productMapper.getProductDetailsById(favorite.getProductId());
            ProductVO productVO = new ProductVO();
            productVO.setId(product.getId());
            productVO.setTitle(product.getTitle());
            productVO.setPrice(product.getPrice());
            productVO.setImage(product.getImage());
            productVOList.add(productVO);
        });
        int count = favoriteMapper.count(userLoginVO.getId());
        PageVO<List<ProductVO>> listPageVO = new PageVO<>(pageDTO.getPageIndex(), pageDTO.getPageSize(),count,productVOList);
        return listPageVO;
    }

    @Override
    public List<ShoppingCartVO> getSettlement(ProductSettlementDTO[] productSettlementDTO,
                                                      UserLoginVO userLoginVO) {
        List<ShoppingCartVO> shoppingCartVOList=new ArrayList<>();
        for (int i = 0; i < productSettlementDTO.length; i++) {
            ShoppingCartVO shoppingCartVO=productMapper.getSettlement(productSettlementDTO[i].getSettlementId(),
                    userLoginVO.getId());
            shoppingCartVO.setTotalPrice(shoppingCartVO.getPrice()*shoppingCartVO.getNum());
            shoppingCartVOList.add(shoppingCartVO);
        }
        return shoppingCartVOList;
    }

    @Override
    public void addProduct(Product product, UserLoginVO userLoginVO){
        //不可以重复增加某商品
        int a1= productMapper.countPid(product.getId());
        if(a1!=0){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"该商品已存在，不可重复添加！");
        }
        //不可以新增其分类不存在的商品
        int a2 = productMapper.countCid(product.getCategoryId());
        if(a2==0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品种类不存在，请重新设置！");
        }
        //封装商品信息
        Product product1 = new Product();
        product1.setId(product.getId());
        product1.setCategoryId(product.getCategoryId());
        product1.setItemType(product.getItemType());
        product1.setTitle(product.getTitle());
        product1.setSellPoint(product.getSellPoint());
        product1.setPrice(product.getPrice());
        product1.setNum(product.getNum());
        product1.setImage(product.getImage());
        product1.setStatus(product.getStatus());
        product1.setPriority(product.getPriority());
        product1.setCreatedUser(userLoginVO.getUsername());
        product1.setModifiedUser(userLoginVO.getUsername());
        Date date = new Date();
        product1.setCreatedTime(date);
        product1.setModifiedTime(date);
        //写入数据库
        int result = productMapper.add(product1);
        if(result != 1){
            throw  new ServiceException(ServiceCode.ERR_UPDATE_FAILED,"新增商品失败");
        }
    }

    @Override
    public void update(Product product, UserLoginVO userLoginVO){
        int a1=productMapper.countPid(product.getId());
        if(a1==0){
            throw  new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在该商品！");
        }
        //封装，product_id，createUser，createTime不能改
        Product product1 = new Product();
        product1.setId(product.getId());
        product1.setCategoryId(product.getCategoryId());
        product1.setItemType(product.getItemType());
        product1.setTitle(product.getTitle());
        product1.setSellPoint(product.getSellPoint());
        product1.setPrice(product.getPrice());
        product1.setNum(product.getNum());
        product1.setImage(product.getImage());
        product1.setStatus(product.getStatus());
        product1.setPriority(product.getPriority());
        product1.setModifiedUser(userLoginVO.getUsername());
        Date date = new Date();
        product1.setModifiedTime(date);
        //写入数据库
        int result = productMapper.update(product1);
        if(result != 1){
            throw  new ServiceException(ServiceCode.ERR_UPDATE_FAILED,"修改商品信息失败");
        }
    }

    /**
     * 后台商品管理--查询商品分页展示
     * @param pageDTO
     * @return
     */
    @Override
    public PageVO<List<ProductBackListVO>> getProductList(PageDTO pageDTO) {
        List<ProductBackListVO> productBackListVOS= new ArrayList<>();
        List<Product> productList = productMapper.getProduct();
        productList.forEach(product ->{
            ProductBackListVO productBackListVO = new ProductBackListVO();
            productBackListVO.setNum(product.getNum());
            productBackListVO.setPrice(product.getPrice());
            productBackListVO.setImage(product.getImage());
            productBackListVO.setId(product.getId());
            productBackListVO.setPriority(product.getPriority());
            productBackListVO.setTitle(product.getTitle());
            productBackListVO.setStatus(product.getStatus());
            productBackListVO.setSellPoint(product.getSellPoint());
            productBackListVO.setItemType(product.getItemType());
            productBackListVO.setCategoryId(product.getCategoryId());
            productBackListVO.setCreatedTime(product.getCreatedTime());
            productBackListVO.setCreatedUser(product.getCreatedUser());
            productBackListVO.setModifiedTime(product.getModifiedTime());
            productBackListVO.setModifiedUser(product.getModifiedUser());
            productBackListVOS.add(productBackListVO);
        });
        //获取这个用户的总收藏商品数据量
        int count = productMapper.count1();
        PageVO<List<ProductBackListVO>> pageVO = new PageVO<>(pageDTO.getPageIndex(),pageDTO.getPageSize(),
                count,productBackListVOS);
        return pageVO;
//        return productBackListVOS;
    }

    /**
     * 后台商品管理--删除商品
     * @param id
     */
    @Override
    public void deleteProduct(Integer id) {
        // 删除
        int result = productMapper.delete(id);
        if(result != 1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"删除失败");
        }
    }

    /**
     * 后台商品管理--商品上架
     */
    @Override
    public void grounding(Integer id) {
        //上架商品
        int result = productMapper.grounding(id);
        if(result !=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"商品上架失败");
        }
    }

    /**
     * 后台商品管理--商品下架
     */
    @Override
    public void offShelf(Integer id) {
        int result = productMapper.offShelf(id);
        if(result !=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"商品下架失败");
        }
    }
}
